import tkinter as tk
from pystray import Icon, Menu, MenuItem
from PIL import Image, ImageDraw
import threading


def create_image():
    """创建托盘图标的图像"""
    width = 64
    height = 64
    color1 = "blue"
    color2 = "white"

    # 创建图像
    image = Image.new("RGB", (width, height), color1)
    draw = ImageDraw.Draw(image)
    draw.rectangle(
        (width // 4, height // 4, width * 3 // 4, height * 3 // 4),
        fill=color2,
    )
    return image


def show_window():
    """恢复窗口"""
    root.deiconify()  # 显示窗口


def quit_app(icon, item):
    """退出程序"""
    icon.stop()  # 停止托盘图标
    root.quit()  # 退出主程序


def minimize_to_tray():
    """最小化到系统托盘"""
    root.withdraw()  # 隐藏窗口

    # 创建托盘图标和菜单
    menu = Menu(
        MenuItem("显示窗口", lambda: show_window()),
        MenuItem("退出", lambda icon, item: quit_app(icon, item))
    )
    icon = Icon("Test App", create_image(), "Python App", menu)

    # 在子线程中运行托盘图标（避免阻塞主线程）
    threading.Thread(target=icon.run, daemon=True).start()


# 创建主窗口
root = tk.Tk()
root.title("最小化到系统托盘")
root.geometry("300x200")

# 添加一个按钮用于最小化到系统托盘
btn_minimize = tk.Button(root, text="最小化到托盘", command=minimize_to_tray)
btn_minimize.pack(pady=50)

# 启动主循环
root.mainloop()
